package com.shop.loan.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import javax.annotation.Resource;


@Component
public class RedisLockUtil {

    @Autowired
    RedisUtil redisUtil;

    @Resource
    ExpireLock expireLock;

    /**
     * 加锁
     *
     * @param lockKey   加锁的Key
     * @param lockValue value
     * @return
     */
    public boolean lock(Jedis jedis, String lockKey, String lockValue) {
        try {
            SetParams params = SetParams.setParams();
            params.ex(5L);
            params.nx();
            if ("OK".equalsIgnoreCase(jedis.set(lockKey, lockValue, params))) {
                // 获得锁成功
                /**
                 * 开线程给key续命
                 */
                expireLock.expireLock(lockKey, lockValue, 5L, null);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public boolean lock(Jedis jedis, String lockKey, String lockValue, Long maxTime) {
        try {
            SetParams params = SetParams.setParams();
            params.ex(5L);
            params.nx();
            if ("OK".equalsIgnoreCase(jedis.set(lockKey, lockValue, params))) {
                // 获得锁成功
                /**
                 * 开线程给key续命
                 */
                expireLock.expireLock(lockKey, lockValue, 5L, maxTime);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 释放锁
     *
     * @param lockKey
     * @param lockValue
     */
    public void release(Jedis jedis, String lockKey, String lockValue) {
        try {
            String currentValue = jedis.get(lockKey);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(lockValue)) {
                // 删除锁
                jedis.del(lockKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
